﻿<template>
  <el-container>
    <el-header>
      <div class="left-panel">
        <el-button
          :icon="Save"
           
          type="primary"
          @click="saveData"
        >
          保存
        </el-button>
        <el-button
          :icon="Search"
           
          type="primary"
          @click="opBatchEdit"
        >
          批量设置
        </el-button>
      </div>
      <div class="right-panel">
        <el-button
          :icon="Search"
           
          type="primary"
          @click="opBindData"
        >
          查询
        </el-button>
        <el-button :icon="Search" type="info" plain @click="resetSearch">
          重置
        </el-button>
        <el-button text type="primary" @click="showCondition = !showCondition">
          <span v-if="!showCondition">展开</span>
          <span v-else>收起</span>
          <vab-icon
            class="vab-dropdown"
            :class="{ 'vab-dropdown-active': fold }"
            icon="arrow-up-s-line"
          />
        </el-button>
      </div>
    </el-header>
    <el-foot v-show="showCondition">
      <vab-query-form-top-panel>
        <el-form
          inline
          label-width="49px"
          :model="queryForm"
          style="margin-top: 5px"
        >
          <el-form-item label="帐号" label-width="100px">
            <el-input
              placeholder="---请输入帐号---"
              v-model="queryList.Code"
              style="width: 300px" /></el-form-item
          ><el-form-item label="姓名" label-width="100px">
            <el-input
              placeholder="---请输入姓名---"
              v-model="queryList.Name"
              style="width: 300px" /></el-form-item
          ><el-form-item label="机构" label-width="100px">
            <el-cascader
              style="width: 300px"
              v-model="queryList.OrgCode"
              :props="props1"
              :show-all-levels="false"
              :emitPath="false"
              :options="optionsParentCode"
            /> </el-form-item
          ><el-form-item label="部门" label-width="100px">
            <el-select
              placeholder="---请输入编码---"
              v-model="queryList.DepartCode"
              multiple
              collapse-tags
              style="width: 300px"
            >
              <el-option
                v-for="item in optionsDepartCode"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select> </el-form-item
          ><el-form-item label="性别" label-width="100px">
            <el-select
              placeholder="---请输入编码---"
              v-model="queryList.SexCode"
              multiple
              collapse-tags
              style="width: 300px"
            >
              <el-option
                v-for="item in optionsSexCode"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select> </el-form-item
          ><el-form-item label="职务" label-width="100px">
            <el-select
              placeholder="---请输入编码---"
              v-model="queryList.DutyCode"
              multiple
              collapse-tags
              style="width: 300px"
            >
              <el-option
                v-for="item in optionsDutyCode"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" label-width="100px"
            ><el-select
              placeholder="---请选择状态---"
              v-model="queryList.State"
              style="width: 300px"
              ><el-option label="---请选择---" value="" /><el-option
                label="禁用"
                value="禁用" /><el-option
                label="启用"
                value="启用" /></el-select
          ></el-form-item>
        </el-form>
      </vab-query-form-top-panel>
    </el-foot>
    <el-main class="nopadding">
      <scTable
        ref="mytable"
        @handleSave="saveData"
        :batchEdit="true"
        :queryType="'batch'"
        :rules="rules"
        :attrList="attrList"
        :valueList="valueList"
        :queryList="queryList"
        @selection-change="selectionChange"
        row-key="Code"
        key="Code"
        stripe
      >
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column
          type="index"
          label="序号"
          prop="rownumber"
          width="50"
        ></el-table-column>

        <el-table-column prop="Code" label="帐号" width="120">
          <template #default="scope"
            ><el-input v-model="scope.row.Code" disabled
          /></template>
        </el-table-column>
        <el-table-column prop="Name" label="姓名" width="120">
          <template #default="scope">
            <el-form-item
              :prop="'tableData.' + scope.$index + '.Name'"
              :rules="rules.Name"
              ><el-input v-model="scope.row.Name" /></el-form-item
          ></template>
        </el-table-column>
        <el-table-column prop="OrgName" label="机构名称" width="150">
          <template #default="scope">
            <el-form-item
              :prop="'tableData.' + scope.$index + '.OrgName'"
              :rules="rules.OrgName"
              ><el-input v-model="scope.row.OrgName" disabled /></el-form-item
          ></template>
        </el-table-column>
        <el-table-column prop="DepartCode" label="部门" width="150">
          <template #default="scope">
            <el-form-item
              :prop="'tableData.' + scope.$index + '.DepartCode'"
              :rules="rules.DepartCode"
              ><el-select
                v-model="scope.row.DepartCode"
                placeholder="---请选择---"
              >
                <el-option
                  v-for="item in optionsDepartCode"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                /> </el-select></el-form-item
          ></template>
        </el-table-column>
        <el-table-column prop="SexCode" label="性别" width="120">
          <template #default="scope"
            ><el-select v-model="scope.row.SexCode" placeholder="---请选择---">
              <el-option
                v-for="item in optionsSexCode"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              /> </el-select
          ></template>
        </el-table-column>
        <el-table-column prop="DutyCode" label="职务" width="120">
          <template #default="scope"
            ><el-select v-model="scope.row.DutyCode" placeholder="---请选择---">
              <el-option
                v-for="item in optionsDutyCode"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              /> </el-select
          ></template>
        </el-table-column>
        <el-table-column prop="Mobile" label="手机" width="120">
          <template #default="scope"
            ><el-input v-model="scope.row.Mobile"
          /></template>
        </el-table-column>
        <el-table-column prop="Email" label="Email" width="120">
          <template #default="scope"
            ><el-input v-model="scope.row.Email"
          /></template>
        </el-table-column>
        <el-table-column prop="WeChat" label="微信号" width="150">
          <template #default="scope"
            ><el-input v-model="scope.row.WeChat"
          /></template>
        </el-table-column>
        <el-table-column prop="BirthDate" label="出生年月" width="120">
          <template #default="scope"
            ><el-date-picker
              v-model="scope.row.BirthDate"
              style="width: 100%"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD "
              placeholder="请输入出生年月"
          /></template>
        </el-table-column>
        <el-table-column prop="IdNumber" label="身份证号" width="180">
          <template #default="scope"
            ><el-input v-model="scope.row.IdNumber"
          /></template>
        </el-table-column>
        <el-table-column prop="State" label="客户经理" width="100">
          <template #default="scope"
            ><el-switch
              v-model="scope.row.IsCustomerMan"
              active-value="1"
              inactive-value="0"
          /></template>
        </el-table-column>
        <el-table-column prop="State" label="可点单" width="100">
          <template #default="scope"
            ><el-switch
              v-model="scope.row.AllowOrder"
              active-value="1"
              inactive-value="0"
          /></template>
        </el-table-column>
        <el-table-column prop="State" label="状态" width="100">
          <template #default="scope"
            ><el-switch
              v-model="scope.row.State"
              active-value="1"
              inactive-value="0"
          /></template>
        </el-table-column>
      </scTable>
    </el-main>
  </el-container>

  <batchset-dialog
    v-if="dialogBatchSet"
    ref="batchSetDialog"
    @fatherMethod="setBatchValue"
    @success="handleSaveSuccess"
    @closed="dialogBatchSet = false"
  >
  </batchset-dialog>
</template>

<script>
import batchsetDialog from "./batchset";
import publicjs from "@/api/model/publicjs";
export default {
  name: "UserInfobatch",
  components: {
    batchsetDialog,
    publicjs,
  },
  data() {
    return {
      dialogBatchSet: false,
      //form: { listData: [] },
      showCondition: false,
      selectionRows: [],
      attrList: {
        HasOld: true,
        Name: "UserInfo",
        UseDistinct: false,
        OrgCode: "",
        UseBackUp: false,
        UseGroup: false,
      },
      pKStr: "Code", //主键
      keepList: ["Code","OrgCode"], //保留的字段，如orgcode,state等
      valueList: {
        Code: "Code",
        Name: "Name",
        OrgCode: "OrgCode",
        OrgName: "OrgName",
        DepartCode: "DepartCode",
        SexCode: "SexCode",
        DutyCode: "DutyCode",
        Mobile: "Mobile",
        Email: "Email",
        WeChat: "WeChat",
        BirthDate: "BirthDate",
        IdNumber: "IdNumber",
        IsCustomerMan:"IsCustomerMan",
        AllowOrder:"AllowOrder",
        State: "State",
      },
      queryList: { Code: "", Name: "" },
      rules: {
        Name: [{ required: true, type: "string", message: "请填写" }],
        OrgName: [{ required: true }],
        DepartCode: [{ required: true }],
      },
      props1: {
        checkStrictly: true,
        emitPath: false,
      },
      optionsDepartCode: [],
      optionsSexCode: [],
      optionsDutyCode: [],
    };
  },
  methods: {
    async opBindData() {
      this.$refs.mytable.clearSort();
      this.$refs.mytable.getData();
    },
    opBatchEdit() {
      this.dialogBatchSet = true;
      this.$nextTick(() => {
        if (this.selectionRows.length > 0) this.$refs.batchSetDialog.open();
        else this.$message.success("请选择记录");
      });
    },
    setBatchValue(valueRows) {
      // eslint-disable-next-line no-debugger
    //debugger;
      //alert(valueRows.length);
      this.selectionRows.forEach((row) => {
        valueRows.forEach((element) => {
          switch (element.DataType) {
            case "string":
              if (element.ExendType == "append")
                row[element.Code] += element.Value;
              else row[element.Code] = element.Value;
              break;
            case "array":
              row[element.Code] = element.Value;
              break;
            case "dictionary":
              row[element.Code] = element.Value;
              break;
            case "josn":
              row[element.Code] = element.Value[element.Value.length - 1];
              break;
            case "bool":
              if (element.Value == "True") row[element.Code] = "1";
              else if (element.Value == "False") row[element.Code] = "0";
              else row[element.Code] = element.Value == "True" ? "0" : "1";
              break;
            case "number":
              if (element.ExendState) {
                let oldValue = Number(row[element.Code]); //原始值
                let rateValue = Number(element.ExendValue); //要修改的动态值
                let currentValue = 0; //存储要修改的最终值
                if (element.Exend1) {
                  //是否启用%
                  if (element.ExendSign == "+")
                    currentValue = oldValue * (1 + rateValue / 100);
                  else currentValue = oldValue * (1 - rateValue / 100);
                  if (element.Exend2) currentValue = Math.round(currentValue);
                  row[element.Code] = currentValue;
                } else {
                  if (element.ExendSign == "+")
                    currentValue = oldValue + rateValue;
                  else currentValue = oldValue - rateValue;
                  if (element.Exend2) currentValue = Math.round(currentValue);
                  row[element.Code] = currentValue;
                }
              } else row[element.Code] = element.Value;
              break;
            case "datetime":
              if (element.ExendState) {
                let oldValue = new Date(row[element.Code].replace(/-/g, "/"));
                let currentValue;
                switch (element.Exend3) {
                  case "yy":
                    if (element.ExendSign == "+")
                      currentValue = oldValue.setFullYear(
                        oldValue.setFullYear() + parseInt(element.ExendValue)
                      );
                    else
                      currentValue = oldValue.setFullYear(
                        oldValue.setFullYear() - parseInt(element.ExendValue)
                      );
                    break;
                  case "mo":
                    if (element.ExendSign == "+")
                      currentValue = oldValue.setMonth(
                        oldValue.getMonth() + parseInt(element.ExendValue)
                      );
                    else
                      currentValue = oldValue.setMonth(
                        oldValue.getMonth() - parseInt(element.ExendValue)
                      );
                    break;
                  case "da":
                    if (element.ExendSign == "+")
                      currentValue = oldValue.setDate(
                        oldValue.getDate() + parseInt(element.ExendValue)
                      );
                    else
                      currentValue = oldValue.setDate(
                        oldValue.getDate() - parseInt(element.ExendValue)
                      );
                    break;
                  case "ho":
                    if (element.ExendSign == "+")
                      currentValue = oldValue.setHours(
                        oldValue.getHours() + parseInt(element.ExendValue)
                      );
                    else
                      currentValue = oldValue.setHours(
                        oldValue.getHours() - parseInt(element.ExendValue)
                      );
                    break;
                  case "mi":
                    if (element.ExendSign == "+")
                      currentValue = oldValue.getMinutes(
                        oldValue.getMinutes() + parseInt(element.ExendValue)
                      );
                    else
                      currentValue = oldValue.getMinutes(
                        oldValue.getMinutes() - parseInt(element.ExendValue)
                      );
                    break;
                  case "se":
                    if (element.ExendSign == "+")
                      currentValue = oldValue.setSeconds(
                        oldValue.getSeconds() + parseInt(element.ExendValue)
                      );
                    else
                      currentValue = oldValue.setSeconds(
                        oldValue.getSeconds() - parseInt(element.ExendValue)
                      );
                    break;
                }
                row[element.Code] = currentValue;
              } else row[element.Code] = element.Value;
              break;
          }
        });
      });
      this.dialogBatchSet = false;
    },
    saveData() {
      this.$refs.mytable.validate(async (valid) => {
        if (valid) {
          this.$message.success("全部验证通过");
          // eslint-disable-next-line no-debugger
        //debugger;
          //alert( this.$refs.mytable.form.tableData.length)
          let changeList = this.getChangeValue(
            this.$refs.mytable.form.tableData
          );
          if (changeList.length == 0) {
            alert("没有做修改，无需保存");
            this.isSaveing = false;
            return;
          }
          var head = new publicjs.head();
          publicjs.initHead(head, "save");
          var ed = new publicjs.entitydata(head);
          changeList.forEach((element) => {
            var eo = new publicjs.entityobj();
            eo.AttrList = {
              Name: "UserInfo",
              DoType: "Edit",
              UseDistinct: false,
              OrgCode: "",
              UseBackUp: false,
              UseGroup: false,
            };
            //eo.ValueList = this.entityObj;
            eo.ValueList = element;
            ed.Data.Content.ObjectList.Object.push(eo);
          });

          try {
            var returnValueStr = await this.$API.auth.objProcess.post(ed);
            let returnValue = JSON.parse(returnValueStr);
            // eslint-disable-next-line no-debugger
            //debugger;
            if (returnValue.Result.OpFlag == "1") {
              this.$message.success("操作成功");
              this.isSaveing = false;
              this.visible = false;
              this.loading = false;
              this.$emit("fatherMethod");
            } else {
              this.$message.error("操作失败:" + returnValue.Result.OpMsg);
            }
          } catch (error) {
            this.loading = false;
            //this.emptyText = error.statusText;
            return false;
          }
        } else {
          return false;
        }
      });
    },
    getChangeValue(objData) {
      let newObjList = [];
      objData.forEach((row) => {
        let newObj = {};
        var hasChange = false;
        for (var field in this.valueList) {
          // eslint-disable-next-line no-debugger
        //debugger;
          if (
            field != this.pKStr &&
            ((this.keepList.length > 0 && this.keepList.indexOf(field) == -1) ||
              this.keepList.length == 0)
          )
            if (row[field] != row[field + "_Old"]) {
              // eslint-disable-next-line no-debugger
            //debugger;
              hasChange = true;
              newObj[field] = row[field];
              newObj[field + "_Old"] = row[field + "_Old"];
            }
        }
        if (hasChange) {
          this.keepList.forEach((field) => {
            newObj[field] = row[field];
            newObj[field + "_Old"] = row[field + "_Old"];
          });
          if (this.keepList.indexOf(this.pKStr) == -1) {
            newObj[this.pKStr] = row[this.pKStr];
            newObj[this.pKStr + "_Old"] = row[this.pKStr + "_Old"];
          }
          newObjList.push(newObj);
        }
      });
      return newObjList;
    },
    //表格选择后回调事件
    selectionChange(selection) {
      // eslint-disable-next-line no-debugger
    //debugger;
      this.selectionRows = selection;
    },
    resetSearch() {
      this.queryList.Code = "";
      this.queryList.Name = "";
      this.queryList.DepartCode = "";
      this.queryList.SexCode = "";
      this.queryList.DutyCode = "";
    },
    async initOptions() {
      var head = new publicjs.head();
      publicjs.initHead(head, "getfirstdatasource");
      var ed = new publicjs.entitydata(head);
      var eo = new publicjs.entityobj();
      eo.AttrList = {
        Name: "UserInfo",
        AcceptControl: "OrgCode,DepartCode,SexCode,DutyCode",
        OrgCode: "",
      };
      ed.Data.Content.ObjectList.Object.push(eo);
      try {
        var returnValueStr = await this.$API.auth.objProcess.post(ed);
        var returnValue = JSON.parse(returnValueStr);
        if (returnValue.Result.OpFlag == "1") {
          var objectList = returnValue.Result.Content.ObjectList.Object;
          for (let i = 0; i < objectList.length; i++) {
            let object = objectList[i];
            if (object.Name == "OrgCode") {
              this.optionsOrgCode = eval("(" + object.rows + ")");
            } else if (object.Name == "DepartCode") {
              this.optionsDepartCode = object.rows.row;
            } else if (object.Name == "SexCode") {
              this.optionsSexCode = object.rows.row;
            } else if (object.Name == "DutyCode") {
              this.optionsDutyCode = object.rows.row;
            }
          }
        }
      } catch (error) {
        this.loading = false;
        this.$alert(error.message, "提示", { type: "error" });
        return false;
      }
    },
  },
  mounted() {
    this.initOptions();
    this.opBindData();
  },
};
</script>
